import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { useUserStoreHook } from "@/store/modules/user";

import { ElMessage } from "element-plus";
const userStore = useUserStoreHook();

const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  baseURL: "https://leju.bufan.cloud",
  timeout: 5000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // 设置token
  if (userStore.accessToken) {
    // config.headers.Authorization = `Bearer ${userStore.accessToken}`;
    config.headers["Token"] = `${userStore.accessToken}`;
  }

  // 配置接口国际化
  // config.headers["Accept-Language"] = store.getters.language;
  return config;
});

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { success, message, data } = response.data;
    if (success) {
      return data;
    } else {
      ElMessage.error(message);
      return Promise.reject(new Error(message));
    }
  },
  (error: any) => {
    // 登录超时
    if (
      error.response &&
      error.response.data &&
      error.response.data.code === 401
    ) {
      // store.dispatch("user/logout");
    }
    ElMessage.error(error.message);
    return Promise.reject(error);
  }
);

export default service;
